package com.wink.admin.security;

import com.wink.admin.common.response.ResultCode;
import com.wink.admin.utils.JsonUtil;
import com.wink.admin.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * AuthenticationEntryPoint 用来解决匿名用户访问需要权限才能访问的资源时的异常
 *
 * @author wink
 * @date 2020/11/23 10:22:00
 */
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * 当用户尝试访问需要权限才能的REST资源而不提供Token或者Token错误或者过期时，
     * 将调用此方法发送401响应以及错误信息
     */
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(ResponseUtils.setResult(ResultCode.AUTH_FAIL, authException.getMessage()));
        response.getWriter().flush();
        response.getWriter().close();

        log.warn("token invalid,results:{}", JsonUtil.toStr(ResponseUtils.getResult()));
        MDC.clear();
        // ServletOutputStream out = response.getOutputStream();
        // out.write(JsonUtil.toStr(ResponseUtils.setResult(ResultCode.AUTH_FAIL)).getBytes(StandardCharsets.UTF_8));
    }
}
